<?php
/**
 * <pre>
 * DiabloStudios.Board v1.0
 * 
 * Manage the forums
 * </pre>
 * 
 * @copyright	(c) 2010 DiabloStudios
 * @license		GNU Affero GPL v3 or newer
 * @package		PHP-Fusion
 * @subpackage	DiabloStudios.Board
 * @link		http://diablostudios.pl
 * @version     $Id: settings.php 1 2011-03-20 11:56:30Z Bartek $
 */

if (!defined("IN_FUSION"))
	die('Access Denied!');
require_once (DSB_LANGDIR . "admin_settings.php");
require_once (DSB_DIR . "includes/admin_functions.php");


// Change settings for a specified group.
if($dsb->input['action'] == "change")
{

	echo "<br />";
	if($dsb->request_method == "post")
	{
		if(is_array($dsb->input['upsetting']))
		{
			foreach($dsb->input['upsetting'] as $name => $value)
			{
				$value = dsb_escape_string($value);
				dbupdate(DB_DSB_SETTINGS, array('value' => $value), "name='".dsb_escape_string($name)."'");
			}
		}
		
		// Check if we need to create our fulltext index after changing the search mode
		if($dsb->settings['searchtype'] != $dsb->input['upsetting']['searchtype'] && $dsb->input['upsetting']['searchtype'] == "fulltext")
		{
			if(!$db->is_fulltext("posts") && $db->supports_fulltext_boolean("posts"))
			{
				$db->create_fulltext_index("posts", "message");
			}
			if(!$db->is_fulltext("posts") && $db->supports_fulltext("threads"))
			{
				$db->create_fulltext_index("threads", "subject");
			}
		}

		// If the delayedthreadviews setting was changed, enable or disable the tasks for it.
		if(isset($dsb->input['upsetting']['delayedthreadviews']) && $dsb->settings['delayedthreadviews'] != $dsb->input['upsetting']['delayedthreadviews'])
		{
			if($dsb->input['upsetting']['delayedthreadviews'] == 0)
			{
				$updated_task = array(
					"enabled" => 0
				);
			}
			else
			{
				$updated_task = array(
					"enabled" => 1
				);
			}
			$db->update_query("tasks", $updated_task, "file='threadviews'");
		}
		
		// Have we changed our cookie prefix? If so, update our adminsid so we're not logged out
		if($dsb->input['upsetting']['cookieprefix'] && $dsb->input['upsetting']['cookieprefix'] != $dsb->settings['cookieprefix'])
		{
			my_unsetcookie("adminsid");
			$dsb->settings['cookieprefix'] = $dsb->input['upsetting']['cookieprefix'];
			my_setcookie("adminsid", $admin_session['sid']);
		}
		
		rebuild_settings();
		

			
		// Log admin action
		//log_admin_action();

		//flash_message($locale['success_settings_updated'], 'success');
		redirect("index.php{$aidlink}&amp;module=settings");
	}
	
	// What type of page
	$cache_groups = $cache_settings = array();
	if($dsb->input['gid'])
	{
		// Group listing
		// Cache groups
		$query = dbquery("SELECT * FROM ".DB_DSB_SETTINGGROUPS." WHERE gid = '".intval($dsb->input['gid'])."'");
		$groupinfo = dbarray($query);
		$cache_groups[$groupinfo['gid']] = $groupinfo;
		
		if(!dbrows($query))
		{
			output_error($locale['error_invalid_gid2']);
		}
		
		// Cache settings
		$query = dbquery("SELECT * FROM ".DB_DSB_SETTINGS." WHERE gid='".intval($dsb->input['gid'])."' ORDER BY disporder");
		while($setting = dbarray($query))
		{
			$cache_settings[$setting['gid']][$setting['sid']] = $setting;
		}
		
		if(!dbrows($query))
        {
            flash_message($locale['error_no_settings_found'], 'error');
            admin_redirect("index.php?module=config-settings");    
        }
		
		$group_lang_var = "setting_group_{$groupinfo['name']}";
		if($locale[$group_lang_var])
		{
			$groupinfo['title'] = $locale[$group_lang_var];
		}
		
		// Page header
		//$page->add_breadcrumb_item($groupinfo['title']);
		
		$form = new Form("index.php{$aidlink}&amp;module=settings&amp;action=change", "post", "change");
	
		echo $form->generate_hidden_field("gid", $groupinfo['gid']);
	}
	else
	{
		// All settings list
		// Cache groups
		$query = dbquery("SELECT * FROM ".DB_DSB_SETTINGGROUPS." ORDER BY disporder");
		while($group = dbarray($query))
		{
			$cache_groups[$group['gid']] = $group;
		}
		
		if(dbrows($query))
		{
			output_error($locale['error_invalid_gid2']);
		}
		
		// Cache settings
		$query = dbquery("SELECT * FROM ".DB_DSB_SETTINGS." ORDER BY disporder");
		while($setting = dbarray($query))
		{
			$cache_settings[$setting['gid']][$setting['sid']] = $setting;
		}
		
		// Page header
		//$page->add_breadcrumb_item($locale['show_all_settings']);
		
		$form = new Form("index.php{$aidlink}&amp;module=settings&amp;action=change", "post", "change");
	}

	// Build rest of page
	$buttons[] = $form->generate_submit_button($locale['save_settings'],array('class' => 'button'));
	foreach($cache_groups as $groupinfo)
	{
		$group_lang_var = "setting_group_{$groupinfo['name']}";
		if($locale[$group_lang_var])
		{
			$groupinfo['title'] = $locale[$group_lang_var];
		}
		
		$form_container = new FormContainer($groupinfo['title'],'form_container');
		
		if(empty($cache_settings[$groupinfo['gid']]))
        {
            $form_container->output_cell($locale['error_no_settings_found']);
            $form_container->construct_row();
            
            $form_container->end();
            echo '<br />';
			
            continue;
        }
		
		foreach($cache_settings[$groupinfo['gid']] as $setting)
		{
			$options = "";
			$type = explode("\n", $setting['optionscode']);
			$type[0] = trim($type[0]);
			$element_name = "upsetting[{$setting['name']}]";
			$element_id = "setting_{$setting['name']}";
			if($type[0] == "text" || $type[0] == "")
			{
				$setting_code = $form->generate_text_box($element_name, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "textarea")
			{
				$setting_code = $form->generate_text_area($element_name, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "yesno")
			{
				$setting_code = $form->generate_yes_no_radio($element_name, $setting['value'], true, array('id' => $element_id.'_yes', 'class' => $element_id), array('id' => $element_id.'_no', 'class' => $element_id));
			}
			else if($type[0] == "onoff")
			{
				$setting_code = $form->generate_on_off_radio($element_name, $setting['value'], true, array('id' => $element_id.'_on', 'class' => $element_id), array('id' => $element_id.'_off', 'class' => $element_id));
			}
			else if($type[0] == "cpstyle")
			{
				$dir = @opendir(MYBB_ROOT.$config['admin_dir']."/styles");
				while($folder = readdir($dir))
				{
					if($file != "." && $file != ".." && @file_exists(MYBB_ROOT.$config['admin_dir']."/styles/$folder/main.css"))
					{
						$folders[$folder] = ucfirst($folder);
					}
				}
				closedir($dir);
				ksort($folders);
				$setting_code = $form->generate_select_box($element_name, $folders, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "language") 
			{
				$languages = $locale['get_languages']();
				$setting_code = $form->generate_select_box($element_name, $languages, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "adminlanguage") 
			{
				$languages = $locale['get_languages'](1);
				$setting_code = $form->generate_select_box($element_name, $languages, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "passwordbox")
			{
				$setting_code = $form->generate_password_box($element_name, $setting['value'], array('id' => $element_id));
			}
			else if($type[0] == "php")
			{
				$setting['optionscode'] = substr($setting['optionscode'], 3);
				eval("\$setting_code = \"".$setting['optionscode']."\";");
			}
			else
			{
				for($i=0; $i < count($type); $i++)
				{
					$optionsexp = explode("=", $type[$i]);
					if(!$optionsexp[1])
					{
						continue;
					}
					$title_lang = "setting_{$setting['name']}_{$optionsexp[0]}";
					if($lang->$title_lang)
					{
						$optionsexp[1] = $lang->$title_lang;
					}
					
					if($type[0] == "select")
					{
						$option_list[$optionsexp[0]] = htmlspecialchars_uni($optionsexp[1]);
					}
					else if($type[0] == "radio")
					{
						if($setting['value'] == $optionsexp[0])
						{
							$option_list[$i] = $form->generate_radio_button($element_name, $optionsexp[0], htmlspecialchars_uni($optionsexp[1]), array('id' => $element_id.'_'.$i, "checked" => 1, 'class' => $element_id));
						}
						else
						{
							$option_list[$i] = $form->generate_radio_button($element_name, $optionsexp[0], htmlspecialchars_uni($optionsexp[1]), array('id' => $element_id.'_'.$i, 'class' => $element_id));
						}
					}
					else if($type[0] == "checkbox")
					{
						if($setting['value'] == $optionsexp[0])
						{
							$option_list[$i] = $form->generate_check_box($element_name, $optionsexp[0], htmlspecialchars_uni($optionsexp[1]), array('id' => $element_id.'_'.$i, "checked" => 1, 'class' => $element_id));
						}
						else
						{
							$option_list[$i] = $form->generate_check_box($element_name, $optionsexp[0], htmlspecialchars_uni($optionsexp[1]), array('id' => $element_id.'_'.$i, 'class' => $element_id));
						}
					}
				}
				if($type[0] == "select")
				{
					$setting_code = $form->generate_select_box($element_name, $option_list, $setting['value'], array('id' => $element_id));
				}
				else
				{
					$setting_code = implode("<br />", $option_list);
				}
				$option_list = array();
			}
			// Do we have a custom language variable for this title or description?
			$title_lang = "setting_".$setting['name'];
			$desc_lang = $title_lang."_desc";
			if($locale[$title_lang])
			{
				$setting['title'] = $locale[$title_lang];
			}
			if($lang->$desc_lang)
			{
				$setting['description'] = $locale[$desc_lang];
			}
			$form_container->output_row(htmlspecialchars_uni($setting['title']), $setting['description'], $setting_code, '', array(), array('id' => 'row_'.$element_id, 'width' => '100%'));
		}
		$form_container->end();
		
		$form->output_submit_wrapper($buttons);
		echo '<br />';
	}
	$form->end();
	
	print_setting_peekers();
	

}

if (!$dsb->input['action'])
{
	echo '<br /><div id="group_list" class="tbl-border">';
	$table = new Table;
	$table->construct_header($locale['setting_groups'], array('style' => 'text-align: left;'));

	$query = dbquery("
				SELECT g.*, COUNT(s.sid) AS settingcount 
				FROM " . DB_DSB_SETTINGGROUPS . " g 
				LEFT JOIN " . DB_DSB_SETTINGS . " s ON (s.gid=g.gid) 
				GROUP BY g.gid
				ORDER BY g.disporder
			");

	while ($group = dbarray($query))
	{
		$group_lang_var = "setting_group_{$group['name']}";
		if ($locale[$group_lang_var])
		{
			$group_title = htmlspecialchars_uni($locale[$group_lang_var]);
		}
		else
		{
			$group_title = htmlspecialchars_uni($group['title']);
		}

		$group_desc_lang_var = "setting_group_{$group['name']}_desc";
		if ($locale[$group_desc_lang_var])
		{
			$group_desc = htmlspecialchars_uni($locale[$group_desc_lang_var]);
		}
		else
		{
			$group_desc = htmlspecialchars_uni($group['description']);
		}

		$table->construct_cell("<strong><a href=\"index.php{$aidlink}&amp;module=settings&amp;action=change&amp;gid={$group['gid']}\">{$group_title}</a></strong> ({$group['settingcount']} {$locale['bbsettings']})<br /><small>{$group_desc}</small>");
		$table->construct_row();
	}
	$table->output("<span style=\"float: right;\"><small><a href=\"index.php{$aidlink}&amp;module=settings&amp;action=change\">{$locale['show_all_settings']}</a></small></span>{$locale['board_settings']}");

	echo '</div>';

	print_setting_peekers();
}

function print_setting_peekers()
{
	echo '<script type="text/javascript" src="./jscripts/peeker.js"></script>
	<script type="text/javascript">
		Event.observe(window, "load", function() {
			loadPeekers();			
		});
		function loadPeekers()
		{
			new Peeker($$(".setting_boardclosed"), $("row_setting_boardclosed_reason"), /1/, true);
			new Peeker($$(".setting_gzipoutput"), $("row_setting_gziplevel"), /1/, true);
			new Peeker($$(".setting_useerrorhandling"), $("row_setting_errorlogmedium"), /1/, true);
			new Peeker($$(".setting_useerrorhandling"), $("row_setting_errortypemedium"), /1/, true);
			new Peeker($$(".setting_useerrorhandling"), $("row_setting_errorloglocation"), /1/, true);
			new Peeker($("setting_subforumsindex"), $("row_setting_subforumsstatusicons"), /[^0]/, false);
			new Peeker($$(".setting_showsimilarthreads"), $("row_setting_similarityrating"), /1/, true);
			new Peeker($$(".setting_showsimilarthreads"), $("row_setting_similarlimit"), /1/, true);
			new Peeker($$(".setting_disableregs"), $("row_setting_regtype"), /0/, true);
			new Peeker($$(".setting_showsimilarthreads"), $("row_setting_similarlimit"), /1/, true);
			new Peeker($("setting_failedlogincount"), $("row_setting_failedlogintime"), /[^0]/, false);
			new Peeker($("setting_failedlogincount"), $("row_setting_failedlogintext"), /[^0]/, false);
			new Peeker($$(".setting_postfloodcheck"), $("row_setting_postfloodsecs"), /1/, true);
			new Peeker($("setting_postmergemins"), $("row_setting_postmergefignore"), /[^0]/, false);
			new Peeker($("setting_postmergemins"), $("row_setting_postmergeuignore"), /[^0]/, false);
			new Peeker($("setting_postmergemins"), $("row_setting_postmergesep"), /[^0]/, false);
			new Peeker($$(".setting_enablememberlist"), $("row_setting_membersperpage"), /1/, true);
			new Peeker($$(".setting_enablememberlist"), $("row_setting_default_memberlist_sortby"), /1/, true);
			new Peeker($$(".setting_enablememberlist"), $("row_setting_default_memberlist_order"), /1/, true);
			new Peeker($$(".setting_enablereputation"), $("row_setting_repsperpage"), /1/, true);
			new Peeker($$(".setting_enablewarningsystem"), $("row_setting_allowcustomwarnings"), /1/, true);
			new Peeker($$(".setting_enablewarningsystem"), $("row_setting_canviewownwarning"), /1/, true);
			new Peeker($$(".setting_enablewarningsystem"), $("row_setting_maxwarningpoints"), /1/, true);
			new Peeker($$(".setting_enablepms"), $("row_setting_pmsallowhtml"), /1/, true);
			new Peeker($$(".setting_enablepms"), $("row_setting_pmsallowmycode"), /1/, true);
			new Peeker($$(".setting_enablepms"), $("row_setting_pmsallowsmilies"), /1/, true);
			new Peeker($$(".setting_enablepms"), $("row_setting_pmsallowimgcode"), /1/, true);
			new Peeker($$(".setting_enablepms"), $("row_setting_pmsallowvideocode"), /1/, true);
			new Peeker($$(".setting_smilieinserter"), $("row_setting_smilieinsertertot"), /1/, true);
			new Peeker($$(".setting_smilieinserter"), $("row_setting_smilieinsertercols"), /1/, true);
			new Peeker($("setting_mail_handler"), $("row_setting_smtp_host"), /smtp/, false);
			new Peeker($("setting_mail_handler"), $("row_setting_smtp_port"), /smtp/, false);
			new Peeker($("setting_mail_handler"), $("row_setting_smtp_user"), /smtp/, false);
			new Peeker($("setting_mail_handler"), $("row_setting_smtp_pass"), /smtp/, false);
			new Peeker($("setting_mail_handler"), $("row_setting_secure_smtp"), /smtp/, false);
			new Peeker($("setting_mail_handler"), $("row_setting_mail_parameters"), /mail/, false);
		}
	</script>';
}

?>